package com.atbeijing.D01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class MyTest {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> streamSource = env.fromElements("hello word", "hello word", "hello word");

        streamSource
            .flatMap(new FlatMapFunction<String, WordWithCount>() {
                @Override
                public void flatMap(String s, Collector<WordWithCount> collector) throws Exception {
                    String[] s1 = s.split(" ");
                    for (int i = 0; i < s1.length; i++) {
                        WordWithCount wordWithCount = new WordWithCount(s1[i],1);
                        collector.collect(wordWithCount);
                    }
                }
            })
            .keyBy(new KeySelector<WordWithCount, String>() {
                @Override
                public String getKey(WordWithCount wordWithCount) throws Exception {
                    return wordWithCount.word;
                }
            })
            .reduce(new ReduceFunction<WordWithCount>() {
                @Override
                public WordWithCount reduce(WordWithCount t1, WordWithCount t2) throws Exception {
                    return new WordWithCount(t1.word,t1.count+t2.count);
                }
            }).print();


        env.execute();
    }


    public static class WordWithCount {
        public String word;
        public long count;

        @Override
        public String toString() {
            return "wordWithCount{" +
                    "word='" + word + '\'' +
                    ", count=" + count +
                    '}';
        }

        public WordWithCount(String word, long count) {
            this.word = word;
            this.count = count;
        }

        public WordWithCount() {
        }
    }
}
